package com.estock.platform.task;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.quartz.JobExecutionException;
import org.springframework.stereotype.Component;

import com.estock.common.model.Pair;
import com.estock.common.model.security.Index;
import com.estock.common.util.CommonUtil;
import com.estock.common.util.support.ESLogger;
import com.estock.common.util.support.IndexPreCodeAndType;
import com.estock.platform.http.SinaIndexBulkConn;
import com.estock.platform.http.response.SinaIndexBulkResponse;
import com.estock.platform.manager.DBManager;
import com.estock.platform.task.support.ESJob;

/**
 * Suggest it to be executed on a weekly basis.
 * 
 * @author richard
 * 
 */
@Component
public class IndexGetter extends ESJob {
	
	private static final int BULK_SIZE = 20;

	private static ESLogger logger = ESLogger.getLogger(IndexGetter.class);
	
	int bulkSize = 0;
	int requestedNum = 0;
	int savedNum = 0;

	@Override
	protected void executeJob() {
		logger.info("start executing job: IndexGetter at "
				+ new Date());

		List<Index> dummyIndexes = generateDummyIndexes();
		List<Index> bulkIndexes = new ArrayList<Index>(10);
		while (requestedNum < dummyIndexes.size()) {
			while (bulkSize < BULK_SIZE && requestedNum < dummyIndexes.size()) {
				bulkIndexes.add(dummyIndexes.get(requestedNum));
				bulkSize++;
				requestedNum++;
			}
			
			try {
				requestAndSave(bulkIndexes);
			} catch (Exception e) {
				// continue
			}
			
			bulkSize = 0;
			bulkIndexes.clear();
		}
		
		logger.info("Try to request dummy %s indexes, saved %s indexes", requestedNum, savedNum);
	}
	
	protected void requestAndSave(List<Index> bulkIndexes) throws Exception {
		SinaIndexBulkResponse response =  (SinaIndexBulkResponse) new SinaIndexBulkConn().request(bulkIndexes, false);
		List<Index> indexes = response.getIndexes();
		for (Index index : indexes) {
			try {
				DBManager.getInstance().saveOrUpdate(index);
				savedNum++;
			} catch (Exception e) {
				// continue
			}
		}
	}

	protected List<Index> generateDummyIndexes() {
		List<Pair> indexPreCodeAndTypes = IndexPreCodeAndType.getIndexPrecodeAndType();
		List<Index> indexes = new ArrayList<Index>();
		for (Pair pair : indexPreCodeAndTypes) {
			String code = String.valueOf(pair.getFirst());
			int indexType = Integer.valueOf(String.valueOf(pair.getSecond()));
			indexes.add(new Index(code, indexType));
		}
		return indexes;
	}

	public static void main(String[] args) throws JobExecutionException {
		CommonUtil.isUnitTest = true;
        
		new IndexGetter().executeJob();
		
		CommonUtil.isUnitTest = false;
	}

}
